package com.mlink.vs.action;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.GZIPInputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.seasar.struts.annotation.Execute;

import com.google.gson.Gson;
import com.mlink.vs.entity.FenceAlarmInfo;
import com.mlink.vs.entity.FenceAlarmInfoAlarm;
import com.mlink.vs.entity.PiccFence;
import com.mlink.vs.entity.PiccFenceAlarm;
import com.mlink.vs.entity.PiccUserSignin;
import com.mlink.vs.service.PiccFenceAlarmService;
import com.mlink.vs.service.PiccFenceService;
import com.mlink.vs.service.PiccUserSigninService;
import com.mlink.vs.util.StreamUtil;

/**
 * 
 * 百度地图API回调接口 zhouhd
 * 
 */
public class BaiduMapAction {

	@Resource
	private HttpServletRequest req;

	@Resource
	private HttpServletResponse rep;

	@Resource
	PiccFenceService piccFenceService;
	@Resource
	PiccFenceAlarmService piccFenceAlarmService;
	@Resource
	PiccUserSigninService piccUserSigninService;

	//http://dazhi.viphk.ngrok.org/videosurvey/baiduMap/call
	@Execute(validator = false)
	public String call1() {
		 System.out.println("鹰眼告警信息回调");
		String gzipFlag = (String) req.getHeader("Content-Encoding");
		 System.out.println("gzipFlag=" + gzipFlag);
		
		String sdata = "";
		if ("gzip".equals(gzipFlag)) {
			// gzip解压缩
			sdata = uncompressToString( req);
		} else {
			// 未压缩直接处理
			StringBuffer indata = StreamUtil.getRequestBody(req);
			sdata = indata.toString();
		}
		
		

//		/ System.out.println("indata=" + sdata);
		Gson gson = new Gson();
		Map<String, Double> mapData = new HashMap<String, Double>();
		mapData = gson.fromJson(sdata, Map.class);
		if (mapData == null)
			return null;
		
		Double type =  (Double) mapData.get("type");
		
		
	
		int iType = 0;
		// double service_id = (double) mapData.get("service_id");
//
		 if (type >= 1d && type < 2d)
		 iType = 1;
		 if (type >= 2d)
		 iType = 2;

		switch (iType) {
		case 1:
			rep.setCharacterEncoding("utf-8");
			rep.setHeader("SignId", "baidu_yingyan");
			rep.setHeader("Content-Type", "application/json");
			try {
				rep.getWriter().println(processType1());
				rep.getWriter().flush();
			} catch (IOException e) {
				// e.printStackTrace();
			}
			break;
		case 2:
			rep.setCharacterEncoding("utf-8");
			rep.setHeader("SignId", "baidu_yingyan");
			rep.setHeader("Content-Type", "application/json");
			try {
				rep.getWriter().println(processType2( sdata ));
				rep.getWriter().flush();
			} catch (IOException e) {
				e.printStackTrace();
			}

			break;
		}

		return null;
	}

	/**
	 * 服务检测
	 * 
	 * @return
	 */
	String processType1() {
		Gson g = new Gson();
		Map m = new HashMap();
		m.put("status", 0d);
		m.put("message", "成功");
		return g.toJson(m);
	}

	/**
	 * 围栏报警百度回调接口
	 * 
	 * @param mapData
	 * @return
	 */
	String processType2(String indata ) {

		Gson gson = new Gson();
		Map<String, String> stsMap = new HashMap<String, String>();
		System.out.println("-----baidu callback-----" + indata.toString());
		FenceAlarmInfo result = gson.fromJson(indata.toString(), FenceAlarmInfo.class);

		if (result == null)
			return null;

		for (int i = 0; i < result.content.size(); i++) {
			FenceAlarmInfoAlarm alarm = result.content.get(i);
			PiccFence piccFence = piccFenceService.findByFenceId(alarm.fence_id+ "");
			
			if(piccFence == null) {
				System.out.println("-----baidu callback-----no found fenceid " );
				continue;
			}
			// 0 电子围栏 1签到围栏

			// 出点子围栏报警
			if (piccFence.fenceType.equals("0") && alarm.action.equals("exit")) {
//				if (piccFence != null) {
				PiccFenceAlarm piccFenceAlarm = new PiccFenceAlarm();
				
				piccFenceAlarm.id = UUID.randomUUID().toString().replace("-", "");
				
				piccFenceAlarm.fenceGroupId = piccFence.fenceGroupId;
				
				piccFenceAlarm.fenceId = alarm.fence_id+"";
				
				piccFenceAlarm.fenceName = alarm.fence_name+"";
				
				if(alarm.action.equals("enter")){
					piccFenceAlarm.action = "0";
				} else {
					piccFenceAlarm.action = "1";
				}
				
				piccFenceAlarm.monitoredPerson =  alarm.monitored_person;
				
				piccFenceAlarm.alarmLat= alarm.alarm_point.latitude+"";
				piccFenceAlarm.alarmLon= alarm.alarm_point.longitude+"";
				piccFenceAlarm.alarmRadius= alarm.alarm_point.radius+"";

				String date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.alarm_point.loc_time*1000l));  
				piccFenceAlarm.alarmLocTime= date;
				
				String date1 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.alarm_point.create_time*1000l));  
				piccFenceAlarm.alarmCreateTime= date1;
				
				
				piccFenceAlarm.preLat= alarm.pre_point.latitude+"";
				piccFenceAlarm.preLon= alarm.pre_point.longitude+"";
				piccFenceAlarm.preRadius= alarm.pre_point.radius+"";
				
				 date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.pre_point.loc_time*1000l));  
				piccFenceAlarm.preLocTime= date;
				
				 date1 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.pre_point.create_time*1000l));  
				piccFenceAlarm.preCreateTime= date1;
				piccFenceAlarmService.insert(piccFenceAlarm);
				
			}
			
			// 签到
			if (piccFence.fenceType.equals("1") && alarm.action.equals("enter")) {
				
				// 先判断今天是否签到
				String date = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date(alarm.pre_point.loc_time*1000l)); 
				int num =  piccUserSigninService.findTotalCount(alarm.monitored_person, date);	
				// 插入签到
				if(num<=0) {
	
				
					 date = new java.text.SimpleDateFormat("HH:mm:ss").format(new java.util.Date(alarm.alarm_point.loc_time*1000l));  
					DateFormat df = new SimpleDateFormat("HH:mm:ss");
			        try {
						Date cur = df.parse(date);
				         Date start = df.parse(piccFence.signinStart);//将字符串转换为date类型  
				         Date end = df.parse(piccFence.signinEnd);  
				         if(start.getTime() <cur.getTime() && cur.getTime()<end.getTime()) {
				        		
								String date2 = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date(alarm.alarm_point.loc_time*1000l));  
								String date3 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.alarm_point.loc_time*1000l));  
						
								PiccUserSignin piccUserSignin = new PiccUserSignin();
								
								piccUserSignin.id = UUID.randomUUID().toString().replace("-", "");
								piccUserSignin.userId = alarm.monitored_person;
								piccUserSignin.signinDate = date2;
								
								piccUserSignin.signinTime = date3;

								piccUserSignin.fenceId = alarm.fence_id+"";
								
								piccUserSignin.fenceName = alarm.fence_name+"";
								
								if(alarm.action.equals("enter")){
									piccUserSignin.action = "0";
								} else {
									piccUserSignin.action = "1";
								}
								piccUserSignin.monitoredPerson =  alarm.monitored_person;
								
								piccUserSignin.alarmLat= alarm.alarm_point.latitude+"";
								piccUserSignin.alarmLon= alarm.alarm_point.longitude+"";
								piccUserSignin.alarmRadius= alarm.alarm_point.radius+"";

								 date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.alarm_point.loc_time*1000l));  
								piccUserSignin.alarmLocTime= date;
								
								String date1 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.alarm_point.create_time*1000l));  
								piccUserSignin.alarmCreateTime= date1;
								
								
								piccUserSignin.preLat= alarm.pre_point.latitude+"";
								piccUserSignin.preLon= alarm.pre_point.longitude+"";
								piccUserSignin.preRadius= alarm.pre_point.radius+"";
								
								 date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.pre_point.loc_time*1000l));  
								 piccUserSignin.preLocTime= date;
								
								 date1 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.pre_point.create_time*1000l));  
								 piccUserSignin.preCreateTime= date1;
								 piccUserSigninService.insert(piccUserSignin);	
				        	 
				         }
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}

		}

		Gson g = new Gson();
		Map m = new HashMap();
		m.put("status", 0d);
		m.put("message", "成功");
		return g.toJson(m);
	
		


	}

	// 测试报警
	@Execute(validator = false)
	public String callTest() {		
		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);
		Map<String, String> stsMap = new HashMap<String, String>();

		FenceAlarmInfo result = gson.fromJson(indata.toString(), FenceAlarmInfo.class);

		if (result == null)
			return null;

		for (int i = 0; i < result.content.size(); i++) {
			FenceAlarmInfoAlarm alarm = result.content.get(i);
			PiccFence piccFence = piccFenceService.findByFenceId(alarm.fence_id+ "");
			// 0 电子围栏 1签到围栏

			// 出点子围栏报警
			if (piccFence.fenceType.equals("0") && alarm.action.equals("exit")) {
				
				PiccFenceAlarm piccFenceAlarm = new PiccFenceAlarm();
				
				piccFenceAlarm.id = UUID.randomUUID().toString().replace("-", "");
				
				piccFenceAlarm.fenceId = alarm.fence_id+"";
				
				piccFenceAlarm.fenceName = alarm.fence_name+"";
				
				if(alarm.action.equals("enter")){
					piccFenceAlarm.action = "0";
				} else {
					piccFenceAlarm.action = "1";
				}
				
				piccFenceAlarm.monitoredPerson =  alarm.monitored_person;
				
				piccFenceAlarm.alarmLat= alarm.alarm_point.latitude+"";
				piccFenceAlarm.alarmLon= alarm.alarm_point.longitude+"";
				piccFenceAlarm.alarmRadius= alarm.alarm_point.radius+"";

				String date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.alarm_point.loc_time*1000l));  
				piccFenceAlarm.alarmLocTime= date;
				
				String date1 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.alarm_point.create_time*1000l));  
				piccFenceAlarm.alarmCreateTime= date1;
				
				
				piccFenceAlarm.preLat= alarm.pre_point.latitude+"";
				piccFenceAlarm.preLon= alarm.pre_point.longitude+"";
				piccFenceAlarm.preRadius= alarm.pre_point.radius+"";
				
				 date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.pre_point.loc_time*1000l));  
				piccFenceAlarm.preLocTime= date;
				
				 date1 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.pre_point.create_time*1000l));  
				piccFenceAlarm.preCreateTime= date1;
				
				piccFenceAlarmService.insert(piccFenceAlarm);
				
			}
			
			// 签到
			if (piccFence.fenceType.equals("1") && alarm.action.equals("enter")) {
				
				// 先判断今天是否签到
				String date = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date(alarm.pre_point.loc_time*1000l)); 
				int num =  piccUserSigninService.findTotalCount(alarm.monitored_person, date);	
				// 插入签到
				if(num<=0) {
	
				
					 date = new java.text.SimpleDateFormat("HH:mm:ss").format(new java.util.Date(alarm.alarm_point.loc_time*1000l));  
					DateFormat df = new SimpleDateFormat("HH:mm:ss");
			        try {
						Date cur = df.parse(date);
				         Date start = df.parse(piccFence.signinStart);//将字符串转换为date类型  
				         Date end = df.parse(piccFence.signinEnd);  
				         if(start.getTime() <cur.getTime() && cur.getTime()<end.getTime()) {
				        		
								String date2 = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date(alarm.alarm_point.loc_time*1000l));  
								String date3 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.alarm_point.loc_time*1000l));  
						
								PiccUserSignin piccUserSignin = new PiccUserSignin();
								
								piccUserSignin.id = UUID.randomUUID().toString().replace("-", "");
								piccUserSignin.userId = alarm.monitored_person;
								piccUserSignin.signinDate = date2;
								
								piccUserSignin.signinTime = date3;

								piccUserSignin.fenceId = alarm.fence_id+"";
								
								piccUserSignin.fenceName = alarm.fence_name+"";
								
								if(alarm.action.equals("enter")){
									piccUserSignin.action = "0";
								} else {
									piccUserSignin.action = "1";
								}
								piccUserSignin.monitoredPerson =  alarm.monitored_person;
								
								piccUserSignin.alarmLat= alarm.alarm_point.latitude+"";
								piccUserSignin.alarmLon= alarm.alarm_point.longitude+"";
								piccUserSignin.alarmRadius= alarm.alarm_point.radius+"";

								 date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.alarm_point.loc_time*1000l));  
								piccUserSignin.alarmLocTime= date;
								
								String date1 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.alarm_point.create_time*1000l));  
								piccUserSignin.alarmCreateTime= date1;
								
								
								piccUserSignin.preLat= alarm.pre_point.latitude+"";
								piccUserSignin.preLon= alarm.pre_point.longitude+"";
								piccUserSignin.preRadius= alarm.pre_point.radius+"";
								
								 date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.pre_point.loc_time*1000l));  
								 piccUserSignin.preLocTime= date;
								
								 date1 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(alarm.pre_point.create_time*1000l));  
								 piccUserSignin.preCreateTime= date1;
								 piccUserSigninService.insert(piccUserSignin);	
				        	 
				         }
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}

		}

		try {
			stsMap.put("sts", "0");
			stsMap.put("msg", "成功");
			rep.setCharacterEncoding("utf-8");
			rep.getWriter().println(gson.toJson(stsMap));
			rep.getWriter().flush();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	/**
	 * GZIP解压缩
	 * 
	 * @param bytes
	 * @return
	 */
	public static byte[] uncompress(byte[] bytes) {
		if (bytes == null || bytes.length == 0) {
			return null;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		try {
			GZIPInputStream ungzip = new GZIPInputStream(in);
			byte[] buffer = new byte[256];
			int n;
			while ((n = ungzip.read(buffer)) >= 0) {
				out.write(buffer, 0, n);
			}
		} catch (IOException e) {

		}

		return out.toByteArray();
	}

	/**
	 * 
	 * @param bytes
	 * @return
	 */
	public static String uncompressToString(	HttpServletRequest req1 ) {

		String encoding = "UTF-8";
		BufferedInputStream in;
		try {

			ByteArrayOutputStream out = new ByteArrayOutputStream();
			GZIPInputStream ungzip = new GZIPInputStream(req1.getInputStream());
			byte[] buffer = new byte[256];
			int n;
			while ((n = ungzip.read(buffer)) >= 0) {
				out.write(buffer, 0, n);
			}
			return out.toString(encoding);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

//		ByteArrayInputStream in = new ByteArrayInputStream(req1.getInputStream());
	
		return null;
	}

	public static String uncompressToString(byte[] bytes, String encoding) {
		if (bytes == null || bytes.length == 0) {
			return null;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		try {
			GZIPInputStream ungzip = new GZIPInputStream(in);
			byte[] buffer = new byte[256];
			int n;
			while ((n = ungzip.read(buffer)) >= 0) {
				out.write(buffer, 0, n);
			}
			return out.toString(encoding);
		} catch (IOException e) {
            e.printStackTrace();
		}
		return null;
	}
}
